package function;

import util.DBConnectionUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashSet;

public class StatisticsCalculator {
    public void calculateStatistics() {
        String sql = "SELECT user_id, behavior_type, item_count, payment_amount FROM user_behavior";
        HashSet<String> visitors = new HashSet<>();
        int addToCartCount = 0;
        double paymentAmount = 0;

        try (Connection conn = DBConnectionUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                String userId = rs.getString("user_id");
                String behaviorType = rs.getString("behavior_type");
                int itemCount = rs.getInt("item_count");
                double payment = rs.getDouble("payment_amount");

                if ("view".equals(behaviorType)) {
                    visitors.add(userId);
                } else if ("add_to_cart".equals(behaviorType)) {
                    addToCartCount += itemCount;
                } else if ("payment".equals(behaviorType)) {
                    paymentAmount += payment;
                }
            }

            int visitorCount = visitors.size();
            insertStatistics(visitorCount, addToCartCount, paymentAmount);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void insertStatistics(int visitorCount, int addToCartCount, double paymentAmount) {
        String sql = "INSERT INTO statistics (visitor_count, add_to_cart_count, payment_amount) VALUES (?,?,?)";
        try (Connection conn = DBConnectionUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, visitorCount);
            pstmt.setInt(2, addToCartCount);
            pstmt.setDouble(3, paymentAmount);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
